<template>
  <j-modal :confirmLoading='confirmLoading' :title='title' :visible='visible' :width='1200' cancelText='关闭'
           switchFullscreen @cancel='handleCancel' @ok='handleOk'>
    <a-divider orientation='left' style='font-weight: 600;margin-top: 0px;'>基本信息</a-divider>
    <a-spin :spinning='confirmLoading'>
      <a-form :form='form'>
        <a-col :md='8' :sm='24'>
          <a-form-item v-if='!itemShow' :labelCol='labelCol' :wrapperCol='wrapperCol' label='选择人员'>
            <a-input-search v-decorator="['visitUserRealName',validatorRules.visitUserRealName]" :disabled='disableSubmit'
                            enter-button placeholder='请选择协访人员' readOnly @search="productSearch2('superiorUser')" />
            <a-input v-decorator="[ 'visitUserName', {}]" readOnly type='hidden' />
          </a-form-item>
        </a-col>
        <a-col :md='8' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='人员职位'>
            <a-input v-decorator="['visitPosName']" :disabled='true' />
          </a-form-item>
        </a-col>
        <a-col :md='8' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属组织'>
            <a-input v-decorator="['departName']" :disabled='true' />
          </a-form-item>
        </a-col>
        <a-col :md='8' :sm='24'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='循环日期'>
            <a-range-picker v-decorator="['visitDates', validatorRules.visitDates]" :format="'YYYY-MM-DD'" :placeholder="['开始时间','结束时间']"
                            :valueFormat="'YYYY-MM-DD'" @change='dateRangeChange'></a-range-picker>
          </a-form-item>
        </a-col>

        <a-divider orientation='left' style='font-weight: 600;margin-top: 0px;'>拜访信息</a-divider>
        <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='排除'>
          <a-radio-group v-model="value" @change="onChange">
            <a-radio :value="1">
              星期一
            </a-radio>
            <a-radio :value="2">
              星期二
            </a-radio>
            <a-radio :value="3">
              星期三
            </a-radio>
            <a-radio :value="4">
              星期四
            </a-radio>
            <a-radio :value="5">
              星期五
            </a-radio>
            <a-radio :value="6">
              星期六
            </a-radio>
            <a-radio :value="7">
              星期日
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-button v-if='!disableSubmit' style='margin: 10px 30px 0px 30px;' type='primary'
                  @click="handleConfigTer(record)">添加经销商
        </a-button>
        <div style='padding: 10px 20px;'>
          <a-table ref='table' :columns='columns2' :dataSource='dataSource' :rowSelection='{selectedRowKeys:selectedRowKeys2, onChange: onSelectChange2}' :scroll='{x:400,y:240 }' bordered
                   rowKey='id' size='middle'
                   @change='handleTableChange'>
            <span slot='action' slot-scope='text, record'>
              <a v-if='!disableSubmit' style='color: red;' @click='handleDelete(record)'>删除</a>
            </span>
          </a-table>
        </div>
        <my-shuttle-modal
          ref='orgShuttleModal'
          :columns='orgColumns'
          :columns2='orgColumns2'
          :positionCode='positionCode'
          :searchConfig='orgSearchConfig'
          keyVal='custCode'
          leftUrl='/customerExtendController/findPageListByPositionCode '
          title='选择经销商'
          @chooseOk='chooseOk'
        ></my-shuttle-modal>
      </a-form>
    </a-spin>
    <StorePlanMod ref="ConfigPosCust" modal-width='90%' @ok='dataUserRess'></StorePlanMod>
    <StorePlanMod ref="ConfigModal" modal-width='90%' @ok="saveUserRelation"></StorePlanMod>
    <!--    <proChose ref="prochoose" name="商品分类" v-bind='modalProps1' @okbro="okbropro1"></proChose>-->
    <!--    <proChose ref="prochoose1" name="线路组" v-bind='modalProps' @okbro="okbropro"></proChose>-->
    <proChose ref='prochoose2' v-bind='modalProps' @okbro='okbropro2'></proChose>
  </j-modal>
</template>

<script>
import {
  httpAction,
  postAction
} from '@/api/manage'
import proChose from '@comp/cn-components/ProChose'

import pick from 'lodash.pick'
import chooseModal from '@/components/cn-components/ChooseModal'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import WedPalnMakingMod from './WedPalnMakingMod.vue'
import StorePlanMod from './StorePlanMod.vue'
import myShuttleModal from '@/components/cn-components/CnShuttleModal'
export default {
  name: 'SfaSignConfigModal',
  components: {
    JTreeSelect,
    chooseModal,
    proChose,
    WedPalnMakingMod,
    StorePlanMod,
    myShuttleModal
  },
  data() {
    return {
      name: '',
      time:'星期一',
      title: '按线网点新增',
      objs: [],
      value: 1,
      positionCode:'', //职位编码
      dataSource: [],
      dataSource2: [],
      lineVos: [],
      visible: false,
      model: {},
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 5
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 16
        }
      },
      //线路组
      columns2: [
        {
          title: '经销商编码',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '经销商类型',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      orgSearchConfig:[
        {
          type:'input',
          placeholder:'经销商编码',
          name:'code'
        },
        {
          type:'input',
          placeholder:'经销商名称',
          name:'name'
        }
      ],
      orgColumns: [
        {
          title: '经销商编码',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'custName'
        }
      ],
      orgColumns2: [
        {
          title: '经销商编码',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'custName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      selectedRowKeys2: [],
      /* table选中records*/
      selectionRows2: [],
      positionsColumns: [
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'terminalCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'terminalName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      //上级用户选择
      productSearch2(status) {
        this.$refs.prochoose2.rowKey = 'id'
        let formconfig = [{
          key: 'userName',
          label: '用户账户'
        },
          {
            key: 'realName',
            label: '用户名称'
          }
        ]
        let tableconfig = {
          columns: [{
            title: '用户账户',
            align: 'left',
            dataIndex: 'userName',
            width: 120,
            ellipsis: true
          },
            {
              title: '用户名称',
              align: 'left',
              dataIndex: 'realName',
              width: 120,
              ellipsis: true
            }
          ],
          list: window._CONFIG['domianURL'] + '/cnUserController/getPageListUser',

          multiple: false,
          columW: 10
        }

        this.name = '用户'
        let dataSource = []
        if (this.form.getFieldValue('superiorUser')) {
          dataSource = [{
            userName: this.form.getFieldValue('superiorUser'),
            realName: this.form.getFieldValue('realsname')
          }]
        }
        this.$refs.prochoose2.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
      },
      rule: [{
        count: 0,
        actCode: '',
        orderNum: '',
        discount: '',
        gifts: []
      }],
      chara: [],
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        visitDates:{
          rules: [{
            required: true,
            message: ''
          }]
        },
        visitUserRealName: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        classifyName:{
          rules: [{
            required: true,
            message: ''
          }]
        },
        classifytotName:{
          rules: [{
            required: true,
            message: ''
          }]
        },
      },
      url: {
        add: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitLineController/saveOrUpdate',
        savePosCust: window._CONFIG['domainURL'] + '/cnTerminalExtendController/saveTerminalExtend',
        saveUserRelation: window._CONFIG['domianURL'] + '/customerExtendController/saveExtendPos',
      }
    }
  },
  computed: {
    modalProps() {
      return {
        name: this.name
      }
    },
    modalProps1() {
      return {
        name: this.name
      }
    }
  },
  methods: {
    // 线路组
    onSelectChange2(selectedRowKeys, selectionRows) {
      this.selectedRowKeys2 = selectedRowKeys
      this.selectionRows2 = selectionRows
    },
    chooseOk(e) {
      let key = this.dataSource.map(item => {
        return item.code
      })
      console.log(e)
      let that = this
      e.forEach(item => {
        if (key.indexOf(item.custCode) == -1) {
          item.code = item.custCode
          item.name = item.custName
          this.dataSource.push(item)
        }
      })
    },
    okbropro2(val, status, status2) {
      let objs = JSON.parse(JSON.stringify(val[0]))
      this.objs = objs
      this.form.setFieldsValue({
        visitUserName: objs.userName,
        visitUserRealName: objs.realName,
        visitPosName: objs.positionName,
        visitPosCode: objs.positionCode,
        departName: objs.departName,
        departCode: objs.departCode,
      })
      this.positionCode = this.objs.positionCode
    },
    showModal(groupCode) {
      this.visible = true;
      console.log(groupCode)
      // this.reqCode = groupCode
      // this.queryParam.groupCode = groupCode
    },
    saveUserRelation(params) {
      console.log(params.posExtendVos)
      this.dataSource2 = params.posExtendVos
      // postAction(this.url.saveUserRelation, this.dataSource2).then(async (res) => {
      //   if (res.success) {
      //     this.$message.success(res.message)
      //     await this.loadData()
      //     this.$refs.ConfigModal.close()
      //   } else {
      //     this.$message.warning(res.message)
      //   }
      // }).finally(() => {
      //   this.$refs.ConfigModal.confirmLoading = false
      //   //that.close();
      // })

    },
    dataUserRess(params) {
      console.log(params)
      this.dataSource = params.posExtendVos
    },
    //经销商删除
    handleDelete(e) {
      let key = this.dataSource.map(item => {
        return item.id
      })
      this.dataSource.splice(key.indexOf(e.id), 1)

    },
    //有效期时间
    addInclude() {
      this.$refs.chooseModal1.show()
    },
    add() {
      this.edit({})
    },
    edit(record,id) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.model.isRoll = this.model.isRoll + ''
      this.model.isControl = this.model.isControl + ''
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'jobStatus', 'signOutStart', 'Position',
          'orgCode', 'visitor'))
      })
    },
    handleConfigTer() {
      this.dataSource.forEach(item => {
        this.$refs.orgShuttleModal.dataSource2.push({ custName: item.name, custCode: item.code })
      })
      this.$refs.orgShuttleModal.visible = true
      this.$refs.orgShuttleModal.loadData()
    },
    savePosCust(params) {

      postAction(this.url.savePosCust, params).then(async (res) => {
        if (res.success) {
          this.$message.success(res.message)
          await this.loadData()
          this.$refs.ConfigPosCust.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.$refs.ConfigPosCust.confirmLoading = false
        //that.close();
      })
    },
    close() {
      this.$emit('close')
      this.form = this.$form.createForm(this),
        this.visible = false
      this.dataSource =[]
      this.dataSource2 =[]
    },

    handleOk() {
      const that = this
      // 触发表单验证
      //经销商
      let dataSource = this.dataSource.map(type => Object.assign({
        clientCode: type.custCode,
        clientName: type.custName,
        longitude:type.longitude,
        latitude:type.latitude,
        clientType: 2
      }))
      this.lineVos = dataSource
      console.log(this.lineVos)
      this.form.validateFields((err, values) => {
        console.log(values)
        that.confirmLoading = true
        let httpurl = ''
        httpurl = this.url.add
        let method = ''
        method = 'post'
        let formData = Object.assign(this.model, values)
        formData.visitPosCode = this.objs.positionCode
        formData.orgCode = this.objs.departCode
        formData.lineVos = this.lineVos
        formData.operType = 1
        console.log(formData)
        //时间格式化
        httpAction(httpurl, formData, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.$emit('ok')
            that.close()
          } else {
            that.$message.warning(res.message)
          }
        }).finally(() => {
          that.confirmLoading = false
        })

      })
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>

<style scoped>

</style>
